def fill_mode(df, columns):
    for col in columns:
        if df[col].dtype == 'object' or df[col].dtype.name == 'category':
            mode = df[col].mode()
            df[col] = df[col].fillna(mode[0] if not mode.empty else 0)
        else:
            median = df[col].median()
            df[col] = df[col].fillna(median)
    return df

def preprocess_city_df(df):
    df = df[df["城乡"].astype(str).str.strip() == "城市"].copy()
    mapping_dict = {
        "社会经济地位同龄比": {"较高": 3, "差不多": 2, "较低": 1, "不好说": 0},
        "社会经济地位三年前比": {"上升了": 3, "差不多": 2, "下降了": 1, "不好说": 0}
    }
    for col, mapping in mapping_dict.items():
        df[col] = df[col].map(mapping)
    if all(col in df.columns for col in mapping_dict):
        df["社会经济地位主观得分"] = df[list(mapping_dict.keys())].mean(axis=1)
    return df
